package com.bookshopsystem.service;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.bookshopsystem.dao.DaoFactory;
import com.bookshopsystem.mod.Order;

/**
 * Servlet implementation class Admin_OrderService
 */
@WebServlet("/Admin_OrderService")
public class Admin_OrderService extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Admin_OrderService() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String type=request.getParameter("type");
		String data;
		JSONArray jsonArray;
		JSONObject jsonObject;
		switch (type) {
		case "orderInfo":
			data=request.getParameter("data");
			jsonObject=new JSONObject().fromObject(data);
			try {
				List<Order> orders=orders=DaoFactory.getOrderDaoInstance().searchOrderAdmin(
						Integer.parseInt(jsonObject.getString("page")),
						Integer.parseInt(jsonObject.getString("pageCount")));
				jsonArray=new JSONArray().fromObject(orders);
				response.getWriter().print(jsonArray);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case "orderCount":
			data=request.getParameter("data");
			try {
				int len=DaoFactory.getOrderDaoInstance().orderPageCount(Integer.parseInt(data));
				System.out.println("orderPage:"+len);
				if (len==0) {
					len=1;
				}
				response.getWriter().print("[{'userPageNum':'"+len+"'}]");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				response.getWriter().print("[{'userPageNum':'1'}]");
			}
			break;
		case "orderDelete":
			data=request.getParameter("data");
			try {
				if (DaoFactory.getOrderDaoInstance().deleteOrderInfo(Integer.parseInt(data))) {
					response.getWriter().print("[{'deleteOrder':'success'}]");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
	}

}
